package com.skywolf.chem.match.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.skywolf.chem.common.config.data.DataSource;
import com.skywolf.chem.common.config.data.DataSourceNames;
import com.skywolf.chem.common.enums.ResponseCodeEnum;
import com.skywolf.chem.common.sysconfig.exception.BizException;
import com.skywolf.chem.match.common.enums.MatchOrderStatusEnum;
import com.skywolf.chem.match.entity.GroupInfo;
import com.skywolf.chem.match.entity.Info;
import com.skywolf.chem.match.entity.Order;
import com.skywolf.chem.match.entity.Sponsor;
import com.skywolf.chem.match.handle.MatchGroupStockHandle;
import com.skywolf.chem.match.mapper.GroupInfoMapper;
import com.skywolf.chem.match.mapper.MatchInfoMapper;
import com.skywolf.chem.match.mapper.OrderMapper;
import com.skywolf.chem.match.params.vo.MatchGroupInfoQueryVo;
import com.skywolf.chem.match.params.vo.MatchGroupPageInfoQueryVo;
import com.skywolf.chem.match.service.IGroupInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skywolf.chem.match.service.IOrderService;
import com.skywolf.chem.match.service.ISponsorService;
import com.skywolf.chem.match.utils.LocalDateUtils;
import com.skywolf.chem.match.utils.SpringContextHolder;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 赛事组别 服务实现类
 * </p>
 *
 * @author
 * @since 2021-09-24
 */
@Service
@AllArgsConstructor
public class GroupInfoServiceImpl extends ServiceImpl<GroupInfoMapper, GroupInfo> implements IGroupInfoService {

    private final GroupInfoMapper groupInfoMapper;

    private final MatchInfoMapper matchInfoMapper;

    private final OrderMapper orderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @DataSource(DataSourceNames.TWO)
    public void delGroupInfo(Long matchId) {
        groupInfoMapper.delGroupInfoByMatchId(matchId);
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public MatchGroupPageInfoQueryVo getMatchInfoById(Long id, Long userId) {
        Info matchInfo = matchInfoMapper.selectById(id);
        if (null == matchInfo) {
            throw new BizException(ResponseCodeEnum.PARAM_ERROR);
        }
        MatchGroupPageInfoQueryVo pageInfoQueryVo = new MatchGroupPageInfoQueryVo();
        pageInfoQueryVo.setMatchName(matchInfo.getMatchName());
        pageInfoQueryVo.setId(matchInfo.getId());
        List<GroupInfo> groupInfoList = groupInfoMapper.selectList(new LambdaQueryWrapper<GroupInfo>().eq(GroupInfo::getMatchId, id));
        if (null == groupInfoList || groupInfoList.size() == 0) {
            pageInfoQueryVo.setGroupInfoList(new ArrayList<>());
            return pageInfoQueryVo;
        }
        List<MatchGroupPageInfoQueryVo.MatchGroupInfoQueryVo> groupInfoQueryVos = groupInfoList.parallelStream().map(item -> {
            MatchGroupPageInfoQueryVo.MatchGroupInfoQueryVo queryVo = new MatchGroupPageInfoQueryVo.MatchGroupInfoQueryVo();
            BeanUtils.copyProperties(item, queryVo);
            queryVo.setCreatedTime(item.getCreatedTime());
            queryVo.setAddress(item.getAddress() + item.getAddressDetail());
            queryVo.setGender(item.getGender());
            ;
            queryVo.setAge(LocalDateUtils.getAge(Date.from(item.getMinAge().atZone(ZoneId.systemDefault()).toInstant())) + "-" + LocalDateUtils.getAge(Date.from(item.getMaxAge().atZone(ZoneId.systemDefault()).toInstant())));
            queryVo.setStatus(item.getGroupState());
            //查询当前用户是否报名过
            Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getMatchGroupId, item.getId()).eq(Order::getMatchUserId, userId).in(Order::getStatus, 101, 201));
            if (null != order) {
                //设置状态为已报名
                queryVo.setStatus(2);
            }
            queryVo.setGroupTypeName(item.getGroupType());
            queryVo.setStock(item.getInitStock());
            queryVo.setSurplusStock(SpringContextHolder.getBean(MatchGroupStockHandle.class).getStockById(item.getId()) - item.getLockedStock());
            queryVo.setMatchTime(LocalDateUtils.format(item.getMatchStartTime(), LocalDateUtils.DATETIME_PATTERN) + " - " + LocalDateUtils.format(item.getMatchEndTime(), LocalDateUtils.DATETIME_PATTERN));
            return queryVo;
        }).sorted(Comparator.comparing(MatchGroupPageInfoQueryVo.MatchGroupInfoQueryVo::getCreatedTime, Comparator.reverseOrder())).collect(Collectors.toList());
        pageInfoQueryVo.setGroupInfoList(groupInfoQueryVos);
        return pageInfoQueryVo;
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public MatchGroupInfoQueryVo getInfo(Long matchId, Long groupId, Long userId) {
        Info matchInfo = matchInfoMapper.selectById(matchId);
        GroupInfo groupInfo = groupInfoMapper.selectById(groupId);

        if (null == matchInfo || null == groupInfo) {
            throw new BizException("参数错误！");
        }
        MatchGroupInfoQueryVo vo = new MatchGroupInfoQueryVo();
        List<Sponsor> sponsorList = SpringContextHolder.getBean(ISponsorService.class)
                .list(new LambdaQueryWrapper<Sponsor>().eq(Sponsor::getMatchId, matchId));
        if (null != sponsorList && sponsorList.size() != 0) {
            vo.setMobileList(sponsorList);
        } else {
            vo.setMobileList(new ArrayList<>());
        }
        vo.setMatchName(matchInfo.getMatchName());
        vo.setId(matchInfo.getId());
        vo.setMatchTypeName(matchInfo.getType());
        MatchGroupInfoQueryVo.MatchGroupDetailInfoQueryVo infoQueryVo = new MatchGroupInfoQueryVo.MatchGroupDetailInfoQueryVo();
        //查询当前用户是否报名过
        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getMatchGroupId, groupId).eq(Order::getMatchUserId, userId).eq(Order::getStatus, MatchOrderStatusEnum.PAYED.getStatus()));
        if (null != order) {
            //设置状态为已报名
            infoQueryVo.setStatus(2);
        }
        BeanUtils.copyProperties(groupInfo, infoQueryVo);
        infoQueryVo.setAge(LocalDateUtils.getAge(Date.from(groupInfo.getMinAge().atZone(ZoneId.systemDefault()).toInstant())) + "-" + LocalDateUtils.getAge(Date.from(groupInfo.getMaxAge().atZone(ZoneId.systemDefault()).toInstant()))
        );
        infoQueryVo.setGroupTypeName(groupInfo.getGroupType());
        infoQueryVo.setStatus(groupInfo.getGroupState());
        infoQueryVo.setStock(groupInfo.getInitStock());
        infoQueryVo.setSurplusStock(SpringContextHolder.getBean(MatchGroupStockHandle.class).getStockById(groupInfo.getId()) - groupInfo.getLockedStock());
        infoQueryVo.setMatchTime(LocalDateUtils.format(groupInfo.getMatchStartTime(), LocalDateUtils.DATETIME_PATTERN) + " - " + LocalDateUtils.format(groupInfo.getMatchEndTime(), LocalDateUtils.DATETIME_PATTERN));
        infoQueryVo.setAddress(groupInfo.getAddress() + groupInfo.getAddressDetail());
        vo.setVo(infoQueryVo);
        return vo;
    }
}
